<template>
  <el-form
    :model="dictype"
    ref="dic"
    :rules="validate_rules"
    label-width="100px"
    style="width:500px"
  >
    <el-form-item label="字典类型" prop="dictype">
      <el-input v-model="dictype.dictype" placeholder="输入字典类型"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">{{
        !$_.isEmpty(dictypeId) ? "立即修改" : "立即创建"
      }}</el-button>
      <el-button @click="$router.push({ path: '/admin/sysdictype' })"
        >取消</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      dictype: { dictype: "" },
      dictypeId: null,
      validate_rules: {
        dictype: [
          {
            validator: (rule, value, callback) => {
              if (this.$_.isEmpty(value)) {
                callback(new Error("字典类型不能为空"));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    onSubmit() {
      this.$refs["dic"].validate(valid => {
        if (valid) {
          this.saveDic();
        } else {
          return false;
        }
      });
    },

    async loadDictypeById() {
      const res = await this.$http.post("/sysdic/getDicTypeById", {
        id: this.dictypeId
      });
      if (res.data.errorCode == "SUCCESS") {
        this.dictype.dictype = res.data.returnData.dicType;
      } else {
        this.$message({
          type: "warning",
          message: res.data.errorMessage
        });
      }
    },

    async saveDic() {
      const post_dic = {
        id: this.dictypeId,
        dicType: this.dictype.dictype
      };
      const res = await this.$http.post("/sysdic/saveDicType", post_dic);
      if (res.data.errorCode == "SUCCESS") {
        this.$message({ type: "success", message: res.data.errorMessage });
      } else {
        this.$message({
          type: "warning",
          message: res.data.errorMessage
        });
      }
    }
  },

  created() {
    this.dictypeId = this.$route.params.id;
    if (!this.$_.isEmpty(this.dictypeId)) {
      this.loadDictypeById();
    }
  }
};
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
